package Exam.model;

import Exam.pojo.User;
import Exam.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class RegisterModel {
    public boolean register(User user) {
        Connection conn = JDBCUtil.getConn();
        try {
            String sqlInsert = "INSERT INTO user (username , pwd , nickname) " +
                    "VALUES ( ? , ? , ?)";
            PreparedStatement psInsert = conn.prepareStatement(sqlInsert);
            psInsert.setString(1, user.getUsername());
            psInsert.setString(2, user.getPassword());
            psInsert.setString(3, user.getNickname());
            psInsert.executeUpdate();
            psInsert.close();
            return true;// 注册成功
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean hasThisName(String username) {

        String sql = "SELECT COUNT(*) FROM user WHERE username = ?";
        Connection conn = JDBCUtil.getConn();
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ResultSet resultSet = ps.executeQuery();
            resultSet.next();
            int count = resultSet.getInt(1);

            resultSet.close();
            ps.close();
            return count > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
